#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   schema.py
@Time    :   2024/02/06 15:51:55
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib
from typing import Any, Optional
from django.db import transaction
from ninja_schema import Schema, ModelSchema, model_validator
from ninja_extra import service_resolver
from ninja_extra.controllers import RouteContext
from ninja_extra.exceptions import APIException

from .models import ArticleCategory
from core.schemas import CoreModelSchema
from system.schema import UserInfoSchema


class CategorySchema(ModelSchema):
    class Config:
        model = ArticleCategory
        include = ["id", "cate_name", "cate_alias"]


class CreateCategorySchema(CoreModelSchema):
    class Config:
        model = ArticleCategory
        include = ["cate_name", "cate_alias"]

    @model_validator("cate_name")
    def unique_name(cls, value_data):
        """
        校验分类名称是否唯一

        Args:
            value_data (str): 分类名称

        Returns:
            str: 唯一的分类名称

        Raises:
            APIException: 分类已存在
        """
        context: RouteContext = service_resolver(RouteContext)
        if context.kwargs.get("id"):
            # 如果存在id参数，则校验分类名称是否唯一且与指定id相关联
            if not ArticleCategory.objects.filter(
                cate_name__contains=value_data,
                creator_id=context.request.user.id,
            ).exclude(id=context.kwargs.get("id")).exists():
                return value_data
        elif not ArticleCategory.objects.filter(
            cate_name__contains=value_data, creator_id=context.request.user.id
        ).exists():
            # 如果不存在id参数，则校验分类名称是否唯一且与当前用户相关联
            return value_data
        raise APIException("分类名称已存在")

    @transaction.atomic
    def create_obj(self, **kwargs: Any):
        context: RouteContext = service_resolver(RouteContext)
        _data = self.dict(exclude_none=True)
        _data["creator"] = context.request.user
        _data["modifier"] = context.request.user.username
        _data.update(kwargs)
        return ArticleCategory.objects.create(**_data)
    
    @transaction.atomic
    def update(self,instance: Any,**kwargs: Any):
        context: RouteContext = service_resolver(RouteContext)
        _data = self.dict(exclude_none=True)
        _data["modifier"] = context.request.user.username
        _data.update(kwargs)
        for attr, value in _data.items():
            setattr(instance, attr, value)
        instance.save()
        return instance
